<?php

/**
 * Controller is the customized base controller class.
 * All controller classes for this application should extend from this base class.
 */
class Controller extends CController
{

    /**
     * @var string the default layout for the controller view. Defaults to '//layouts/column1',
     * meaning using a single column layout. See 'protected/views/layouts/column1.php'.
     */
    public $layout = '//layouts/main';
    public $_m;//样式路径
    /**
     * @var array context menu items. This property will be assigned to {@link CMenu::items}.
     */
    public $menu = array();
    public $pageTitle = '';
    public $keywords = '投资,理财, 网络投资, 草根投资';
    public $description = '草根投资-新型债权B2C理财平台。通过线下+线上，安全性+合法性的服务体系，由浙江拓远律师事务所进行全程监控，为投资人提供一个安全、方便、快捷、高效的投资理财环境。';
    /**
     * @var array the breadcrumbs of the current page. The value of this property will
     * be assigned to {@link CBreadcrumbs::links}. Please refer to {@link CBreadcrumbs::links}
     * for more details on how to specify this property.
     */
    public $breadcrumbs = array();
    public $javaApi;
    public function init()
    {
        $this->_m       = Yii::app()->params["mediaUrl"];
        $this->javaApi  = Yii::app()->params['scripts'];
    }
    /**
     * 单位转换
     * @param type $value
     * @param bool $need
     * @return int
     */
    public function showWan($value,$need=true)
    {
        if ($value <= 0)
            return 0;
        if($need)
        {
            if($value<=999)
                return $value.'元';
            else if($value>=1000 && $value<=9999)
            {
                if($value%1000==0)
                {
                    return round($value / 1000) . '千';
                }else
                {
                    return $value . '元';
                }
            }
        }
        return ($value >= 10000) ? round($value / 10000, 2) . '万' : $value . '元';

    }
    /**
     * 校验用户token
     */
    public function checkUserToken($user_id,$token)
    {
        if(!$user_id || !$token)
            return false;
        if(Yii::app()->cache2->get($user_id.'.ClientAppToken')==$token)
        {
            Yii::app()->cache2->expire($user_id.'.ClientAppToken',3600);
            return true;
        }
        return false;
    }

    /**
     * 计算融资进度
     * @param type $Balance
     * @param type $Amount
     * @return int
     */
    public function converPoint($Balance, $Amount)
    {
        if ($Balance == 0 || $Amount == 0)
            return 100;
        return round((($Amount - $Balance) / $Amount) * 100, 2);
    }

    /**
     * @param $premiumAmount
     * @param $model
     * @return float|int
     */
    public function cacAcode($premiumAmount, $model)
    {
        $yearDays = 360;
        $beginTime = strtotime("2015-03-01 00:00:00");
        $endTime = strtotime($model->onlineTime);
        if($endTime>=$beginTime)
         $yearDays = 365;
        if ($premiumAmount == 0 || $model->totalAmount == 0 || $model->debtDTO->annualizedRate == 0)
            return 0;
        $m = $model->debtDTO->interestFrom;
        $days = 1 + ((strtotime($model->debtDTO->endTime) - strtotime($model->debtDTO->startTime)) / 3600 / 24) - $m;
        $debtTotalAmount = $model->totalAmount * (1 + ($model->debtDTO->annualizedRate / 100) * $days / $yearDays);
        return round((($debtTotalAmount - $premiumAmount) / $premiumAmount) * $yearDays / $days * 100, 2);
    }
    /**
     * 发送短信
     * @param int $userId
     * @param string $mobile
     * @param array $params $params = array('file'=>'','params'=>array('code'=>'123456'));
     * @param string $method 如果$method为voice，则发送语音验证码
     * @return bool
     */
    public function SendSms($userId, $mobile, $params, $method = 'sms')
    {
        if($method=='voice')
        {
            $sess = Yii::app()->session;
            $content = isset($sess['mobileCode'])?$sess['mobileCode']:$params['params']['code'];
        }
        else if($method=='sms')
        {
            if (!isset($params['file'])) {
                return false;
            }
            $smsTemplate = new SmsTemplates();
            $content = $smsTemplate->loadTemplate($params['file'], $params['params']);
        }
        else{
            return false;
        }
        $source = Yii::app()->params['mobile']['source'];
        $smsObj = array(
            'logId'   => '-1',
            'userId'  => $userId,
            'mobile'  => $mobile,
            'content' => $content,
            'source'  => $source,
            'method'  => $method,
            'ifa'     => DEVICESERIALID,
        );
        return Yii::app()->cache->lpush(Yii::app()->params['mobile']['queeMobile'], CJSON::encode($smsObj));
    }

    /*
     * @param string $key
     * @param int $times
     * @return boolen 
     */
    public function sms_disabled($key, $times = 6)
    {
        if (false !== ($sendTimes = Yii::app()->cache->get($key))) {
            Yii::app()->cache->set($key, $sendTimes + 1, 86400);
            return $sendTimes >= $times;
        } else {
            Yii::app()->cache->set($key, $sendTimes + 1, 86400);
            return false;
        }

    }
    public function _post($name, $default = '')
    {
        return trim(Yii::app()->request->getPost($name, $default));
    }

    public function _get($name, $default = '')
    {
        return trim(Yii::app()->request->getParam($name, $default));
    }
    
    public function beforeAction($action)
    {
        if(!Yii::app()->request->isPostRequest && strtolower($this->route) != 'site/captcha')
        {
            echo json_encode(array(
                'success' => 0,
                'msg'     => 'illegal request method',
            ));
            Yii::app()->end();
        }
        if(Yii::app()->cache2->get("cgtz_system_maintaining"))
        {
            echo json_encode(array(
                'success' => 0,
                'action'  => 'maintain',
                'msg'     => '维护中',
            ));
            Yii::app()->end();
        }
        return true;
    }
    private function _getReffer($keywords)
    {
        if($keywords=='')
        {
            return;
        }
        $tmp = $this->_get($keywords);
        if($tmp!='')
        {
            $cookie = new CHttpCookie('source',base64_encode($keywords.'|'.$tmp));
            $cookie->expire = 0;
            Yii::app()->request->cookies[$keywords] = $cookie;
        }else{return;}
    }

    /**
     * 格式化数据
     * @param  [type]  $number        [description]
     * @param  integer $decimals      [description]
     * @param  boolean $she           是否舍去零头 默认四舍五入
     * @param  string  $dec_point     [description]
     * @param  string  $thousands_sep [description]
     * @return [type]                 [description]
     */
    public  function formatNumber($number,$decimals = 0,$she=false,$dec_point = ".", $thousands_sep = "")
    {
        if($she)
        {
            $times = pow(10,$decimals);
            $number = bcmul($number,$times)/$times;
        }
        return number_format($number,$decimals,$dec_point,$thousands_sep);
    }

    /**
     * 把一个数组里的值由null转为空字符串(苹果传null会导致问题)
     */
    public  function formatResult($data)
    {
        if($data && is_array($data))
        {
            foreach($data as $k=>$v)
            {
                if(is_array($v))
                {
                    $v = $this->formatResult($v);
                }
                elseif(is_object($v))
                {
                    $v = (array)$v;
                    $v = $this->formatResult($v);
                }
                else
                {
                    if($v === null)
                        $v = '';
                }
                $data[$k] = $v;
            }
        }
        return $data;
    }
}
